package com.thti.mecool.client.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.model.biz.TaskManageBizImpl;
import com.thti.mecool.client.model.biz.TaskStepBizImpl;
import com.thti.mecool.client.model.po.TaskManage;
import com.thti.mecool.client.model.po.TaskStep;
import com.thti.mecool.client.service.LocateService;
import com.thti.mecool.client.util.StringUtil;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.AlterDialogWidget;
import com.thti.mecool.client.widget.IsOKListener;
import com.thti.mecool.client.widget.Toolbar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TaskStepActionActivity extends BaseActivity {
	private TextView action_text, action_stat;
	private ListView action_list;
	private String[] taskItemName;
	private int[] curActionIds;
	private String action_title = null;
	@SuppressWarnings("unused")
	private Toolbar toolbar;
	private String taskDatatypeName;
	private String planId, projectId, parentId, taskId, parentStepId,storeAddress;
	private String[] StepIds;
	@SuppressWarnings("unused")
	private TaskManageBizImpl taskManageBizImpl;
	private TaskManage taskManage;
	private ArrayList<Integer> isOvers;
	private ArrayList<String> parentIds;
	private HashMap<String, Integer> finishStat;
	private RelativeLayout relativeLayout;
	private String curParentId;
	private ImageButton save, cancel;
	private boolean isMulChoice=false;
	private String stepId;
	private SharedPreferences load;
	@SuppressWarnings("unused")
	private String taskName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		noTitle();
		setContentView(R.layout.mecool_task_action);
		load = getSharedPreferences("LocationService", 0);
		relativeLayout = (RelativeLayout) findViewById(R.id.mecool_task_action_btn);
		save = (ImageButton) findViewById(R.id.mecool_task_action_save);
		cancel = (ImageButton) findViewById(R.id.mecool_task_action_cancel);
		save.setOnClickListener(onClickListener);
		cancel.setOnClickListener(onClickListener);
		Intent in = new Intent(this, LocateService.class);
		in.putExtra("flag", 101);
		startService(in);
		finishStat = new HashMap<String, Integer>();
		isOvers = new ArrayList<Integer>();
		parentIds = new ArrayList<String>();
		action_text = (TextView) findViewById(R.id.mecool_action_text);
		action_stat = (TextView) findViewById(R.id.mecool_action_stat);
		action_list = (ListView) findViewById(R.id.mecool_action_list);
		Intent i = getIntent();
		taskName = i.getStringExtra("taskName");
		planId = i.getStringExtra("planId");
		projectId = i.getStringExtra("projectId");
        taskId = i.getStringExtra("taskId");
		parentStepId = i.getStringExtra("parentStepId");
		parentId = i.getStringExtra("parentId");
		taskDatatypeName = i.getStringExtra("text_name");
		isMulChoice=i.getBooleanExtra("isMulChoice", false);
		storeAddress=i.getStringExtra("storeAddress");
		action_text.setText(taskDatatypeName);
		toolbar = new Toolbar(this);
		Toolbar.hideRightButton();
		Toolbar.left_btn.setImageResource(R.drawable.mecool_go_back);
		Toolbar.left_btn.setOnClickListener(onClickListener);
		
		
		
		getTaskforSQL(parentId);
	  if(!StringUtil.isBlank(taskDatatypeName)){
		if(taskDatatypeName.contains("门店地址")){
			if(!StringUtil.isBlank(storeAddress)){
				action_stat.setText(storeAddress);
			}
		}
	  }
		action_list.setOnItemClickListener(onItemClickListener);
		action_list.setAdapter(action_list_adapter);
		curParentId = parentId;
	}

	private void getTaskforSQL(String parentId) {
		isOvers.clear();
		parentIds.clear();
		finishStat.clear();
		TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
		List<TaskStep> tasks = taskStepBizImpl.findByStep(planId, projectId,
				parentId,taskId);
		StepIds = new String[tasks.size()];
		taskItemName = new String[tasks.size()];
		curActionIds = new int[tasks.size()];
		for (int i = 0; i < tasks.size(); i++) {
			isOvers.add(tasks.get(i).getIsOver());
			if (tasks.get(i).getActionId() == 4) {
				action_title += " - " + tasks.get(i).getName();
				getTaskforSQL(tasks.get(i).getStepId());
				break;
			}
			curActionIds[i] = tasks.get(i).getActionId();
			taskItemName[i] = tasks.get(i).getName();
			StepIds[i] = tasks.get(i).getStepId();
			finishStat.put(tasks.get(i).getStepId(), 0);
			parentIds.add(tasks.get(i).getParentId());
		}
	}

	private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_toolbar_leftbtn:
				finish();
				break;
			case R.id.mecool_task_action_save:
				Util.sendToast(TaskStepActionActivity.this, "保存已经成功！");
				isFinish(1);
				finish();
				break;
			case R.id.mecool_task_action_cancel:
				new AlertDialog.Builder(TaskStepActionActivity.this)
						.setTitle("提示").setMessage("已完成的步骤将被清空，确认要退出吗？")
						.setNegativeButton("取消", dialogClickListener)
						.setPositiveButton("确认", dialogClickListener).create()
						.show();
				break;
			default:
				break;
			}
		}
	};

	public void isFinish(int finish) {
		TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(
				TaskStepActionActivity.this);
		List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
		Map<String, Object[]> map = new HashMap<String, Object[]>();
		String[] ids = new String[] { String.valueOf(finish), planId,
				projectId, parentStepId, taskId };
		map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
		list.add(map);
		taskStepBizImpl.updateStep(list);
	}

	@Override
	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if(isOvers.get(0)==2)
			new AlertDialog.Builder(TaskStepActionActivity.this).setTitle("提示")
					.setMessage("已完成的步骤将被清空，确认要退出吗？")
					.setNegativeButton("取消", dialogClickListener)
					.setPositiveButton("确认", dialogClickListener).create()
					.show();
			else
				return super.onKeyDown(keyCode, event);
		}
		return false;

	};

	private android.content.DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case -1:
				TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(
						TaskStepActionActivity.this);
				List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
				for (int i = 0; i < StepIds.length; i++) {
					Map<String, Object[]> map = new HashMap<String, Object[]>();
					String[] ids = new String[] { "0", planId, projectId,
							StepIds[i], taskId };
					map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
					String[] ids2 = new String[] { null, planId, projectId,
							StepIds[i], taskId };
					map.put(HandlerConstant.TASK_STEP_UPDATE_DATA_SQL, ids2);
					list.add(map);
				}
				taskStepBizImpl.updateStep(list);
				isFinish(0);
				finish();
				break;
			default:
				break;
			}
		}
	};
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			curParentId = parentIds.get(arg2);
			taskManageBizImpl = new TaskManageBizImpl(
					TaskStepActionActivity.this);
			taskManage = new TaskManage();
			int curstat = 0;
			if (curActionIds != null) {
				curstat = curActionIds[arg2];
			}
			if (action_title == null)
				action_title = taskItemName[arg2];
			else if (curstat == 4)
				action_title += " - " + taskItemName[arg2];
			action_stat.setText(action_title);

			// action_stat.setText(action_title);
			Intent i = new Intent();
			stepId = StepIds[arg2];
			taskManage.setPlanId(planId);
			taskManage.setProjectId(projectId);
			taskManage.setTaskId(taskId);
			taskManage.setStepId(StepIds[arg2]);
			taskManage.setIsUpload(0);

			switch (curstat) {
			case 1:
				taskManage.setIsType(1);
				i.setClass(TaskStepActionActivity.this, CameraActivity.class);
				i.putExtra("planId", planId);
				i.putExtra("projectId", projectId);
				i.putExtra("taskId", taskId);
				i.putExtra("StepId", StepIds[arg2]);
				startActivity(i);
				break;
			case 2:
				AlterDialogWidget ad = new AlterDialogWidget(
						TaskStepActionActivity.this);
				ad.setEditTextDialog();
				ad.setReturnView(arg1.findViewWithTag("tv2"));
				ad.setIsOKListener(isOKListener);
				ad.show();
				taskManage.setIsType(2);
				break;
			case 3:
				AlterDialogWidget ad2 = new AlterDialogWidget(
						TaskStepActionActivity.this);
				ad2.setEditTextDialog();
				ad2.setIsNumEt(true);
				ad2.setReturnView(arg1.findViewWithTag("tv2"));
				ad2.setIsOKListener(isOKListener);
				ad2.show();
				taskManage.setIsType(2);
				break;
			case -1:
				if (isOvers.get(arg2) == 1) {
					complete(taskItemName[arg2]);
					List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
					Map<String, Object[]> map = new HashMap<String, Object[]>();
					String[] ids = new String[] { "1", planId, projectId,
							parentStepId, taskId };
					map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
					if(isMulChoice){
						Map<String, Object[]> map2 = new HashMap<String, Object[]>();
						map2.put("update taskStep set data=? where planId=? and projectId=?  and stepId=? and taskId=?", new String[] { taskItemName[arg2], planId, projectId,
								parentId, taskId });
						System.out.println("true  "+parentId+"  taskItemName[arg2]  "+taskItemName[arg2]);
						list.add(map2);
					}
					list.add(map);
					TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(
							TaskStepActionActivity.this);
					taskStepBizImpl.updateStep(list);
					finish();
				} else {
					getTaskforSQL(StepIds[arg2]);
					action_list_adapter.notifyDataSetChanged();
				}
				break;
			case 4:
				getTaskforSQL(StepIds[arg2]);
				action_list_adapter.notifyDataSetChanged();

				break;
			default:

				break;
			}
		}
	};
	private IsOKListener isOKListener = new IsOKListener() {
		@Override
		public void isOk(boolean isPutOk, String content) {
			if (isPutOk) {
				complete(content);
				relativeLayout.setVisibility(0);
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		refresh();
	};

	 public void refresh(){
			TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
			List<TaskStep> taskSteps = taskStepBizImpl.findFinishSteps(projectId,
					taskId, curParentId);
			if (taskSteps.size() > 0) {
				for (TaskStep ts : taskSteps) {
					finishStat.put(ts.getStepId(), 1);
				}
				if (taskSteps.size() == StepIds.length)
					relativeLayout.setVisibility(0);
				action_list_adapter.notifyDataSetChanged();
			}
	 }
	private void complete(String content) {
		taskManage.setData(content);
		taskManage.setLatitude(load.getString("Latitude", null));
		taskManage.setLongitude(load.getString("Longitude", null));
		TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
		List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
		Map<String, Object[]> map = new HashMap<String, Object[]>();
		String[] ids = new String[] { "1", planId, projectId, stepId, taskId };
		map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
		list.add(map);
		taskStepBizImpl.updateStep(list);
		taskStepBizImpl.updateData(taskManage);
		action_list_adapter.notifyDataSetChanged();
	}

	private BaseAdapter action_list_adapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
				convertView = getLayoutInflater().inflate(
						R.layout.mecool_task_action_step_item, null);
				TextView tv = (TextView) convertView
						.findViewById(R.id.mecool_task_action_step_item_title);
				TextView tv2 = (TextView) convertView
						.findViewById(R.id.mecool_task_action_step_item_content);
				ImageView iv = (ImageView) convertView
						.findViewById(R.id.mecool_task_action_step_item_imageview);
			tv.setText(taskItemName[position]);

			TaskStepBizImpl taskStepBizImpl=new TaskStepBizImpl(TaskStepActionActivity.this);
			String data=taskStepBizImpl.findStepData(planId, projectId, taskId, parentIds.get(position),StepIds[position]);
	
			if(data!=null){
				tv2.setText(data);
				tv2.setVisibility(0);
			}
			tv2.setTag("tv2");
			if (tv2.getText().equals(""))
				tv2.setVisibility(8);
			if (finishStat.get(StepIds[position]) == 1) {
				iv.setVisibility(0);
			} else {
				iv.setVisibility(8);
			}
			if(data!=null){
				tv2.setText(data);
				tv2.setVisibility(0);
			}
			// ll.addView(iv);
			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return taskItemName[position];
		}

		@Override
		public int getCount() {
			return taskItemName.length;
		}
	};

	class ViewHolder {
		ImageView iv;
		TextView tv;
		TextView tv2;
	}
}
